package com.cocolover2.andbase;

import android.app.Activity;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * activities 容器
 * Created by cocolove2 on 17/8/8.
 */
@SuppressWarnings("all")
public final class ActivityContainer {
    private final static List<WeakReference<Activity>> mActivityStack = new ArrayList<>();

    private ActivityContainer() {
    }

    private static class ActivityContainerHolder {
        private static final ActivityContainer INSTANCE = new ActivityContainer();
    }

    public static ActivityContainer getInstance() {
        return ActivityContainerHolder.INSTANCE;
    }

    public void addActivity(Activity activity) {
        mActivityStack.add(new WeakReference<Activity>(activity));
    }

    public void removeActivity(Activity activity) {
        Iterator<WeakReference<Activity>> iterator = mActivityStack.iterator();
        while (iterator.hasNext()) {
            WeakReference<Activity> item = iterator.next();
            if (item.get() != null && item.get().equals(activity)) {
                iterator.remove();
                break;
            }
        }
    }

    /**
     * 结束所有Activity
     */
    public void killAllActivity() {
        for (WeakReference<Activity> activity : mActivityStack) {
            if (null != activity.get()) {
                activity.get().finish();
            }
        }
        mActivityStack.clear();
    }

    public void killActivity(Class<? extends Activity> clz) {
        for (WeakReference<Activity> activity : mActivityStack) {
            if (null != activity.get() && activity.get().getClass().getName().equals(clz.getName())) {
                activity.get().finish();
            }
        }
    }

    public void killAllActivityExceptMe(Activity me) {
        for (WeakReference<Activity> activity : mActivityStack) {
            if (null != activity.get() && !activity.get().equals(me)) {
                activity.get().finish();
            }
        }
    }
}
